<template>
  <div id="app">
    <el-container>
      <el-header v-if="$route.path !== '/login'">
        <el-menu
          :default-active="$route.path"
          mode="horizontal"
          router
          :ellipsis="false"
        >
          <el-menu-item index="/">
            首页
          </el-menu-item>
          <el-menu-item index="/products">
            商品管理
          </el-menu-item>
          <el-menu-item index="/users">
            用户管理
          </el-menu-item>
          <el-menu-item index="/orders">
            订单管理
          </el-menu-item>
          <el-menu-item index="/reports">
            举报管理
          </el-menu-item>
        </el-menu>
        <div class="nav-user">
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-icon><UserFilled /></el-icon> 管理员 <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="logout">
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main>
        <div class="main-center">
          <router-view />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import { onMounted, watch } from 'vue'
import { UserFilled, ArrowDown } from '@element-plus/icons-vue'
const router = useRouter()
const route = useRoute()
function checkAuth() {
  const token = localStorage.getItem('token')
  if (!token && route.path !== '/login') {
    router.replace('/login')
  }
  if (token && route.path === '/login') {
    router.replace('/')
  }
}
onMounted(checkAuth)
watch(() => route.path, checkAuth)
function logout() {
  localStorage.removeItem('token')
  router.replace('/login')
}
</script>

<style>
#app {
  min-height: 100vh;
  background: #f5f6fa;
}
.main-center {
  max-width: 1100px;
  margin: 0 auto;
  padding: 32px 0;
}
.el-header {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  box-shadow: 0 2px 8px #f0f1f2;
  position: relative;
}
.el-menu {
  border-bottom: none;
}
.el-menu--horizontal .el-menu__overflow {
  display: none !important;
}
.el-menu--horizontal .el-menu__item {
  min-width: 100px;
  font-size: 16px;
  padding: 0 24px;
}
.nav-user {
  position: absolute;
  right: 32px;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 16px;
  cursor: pointer;
}
</style>
